package com.orgcent.activities;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import com.orgcent.util.Tools;

import android.app.Activity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.widget.TextView;
/**
 * 在线搜索歌词
 */
public class OnlineSearchLyric extends Activity {

	private static final String TAG = OnlineSearchLyric.class.getSimpleName();
	private TextView result_tv;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.online_search_lyric);

		result_tv = (TextView) findViewById(R.id.result_tv);
		
		getWindow().getDecorView().postDelayed(new Runnable() {
			
			@Override
			public void run() {
				String content = searchLyric("青花瓷");
				
				//TODO:对搜索内容使用正则表达式过滤，获取
				//匹配的第一个lrc文件路径.如：
				//"http://www.cnlyric.com//LrcDown/2007-11-2/928182.lrc"
				
				if(TextUtils.isEmpty(content)) {
					result_tv.setText("歌词为空");
				} else {
					result_tv.setText(content);
				}
			}
		},1000);
	}
	
	// 获取网络内容
	private String searchLyric(String keyword) {
		String uri = "";
		try {
			uri = "http://www.baidu.com/s?wd=" + URLEncoder.encode("filetype:lrc " + keyword, "GBK");
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}
		HttpClient client = new DefaultHttpClient();
		HttpGet get = new HttpGet(uri);
		
		get.addHeader("Host", "www.baidu.com");
		get.addHeader("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.8.1.11) Gecko/20071127 Firefox/2.0.0.11");
		get.addHeader("Accept", "text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5");
		get.addHeader("Accept-Language", "zh-cn,zh;q=0.5");
		get.addHeader("Keep-Alive", "300");
		get.addHeader("Referer", "http://www.baidu.com/");
		get.addHeader("Connection", "keep-alive");
		
		HttpResponse resp;
		StringBuilder content = new StringBuilder();
		try {
			resp = client.execute(get);
			HttpEntity entity = resp.getEntity();
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					entity.getContent(), "gbk"));
			String line;
			while ((line = reader.readLine()) != null) {
				content.append(line);
			}
			reader.close();
			entity = null;
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			client.getConnectionManager().shutdown();
		}

		return content.toString();
	}
}
